﻿using AutoMapper;
using ClientBasicData.Api.Application.Command;
using ClientBasicData.Domain.Client;
using ClientBasicData.ErrorCode;
using ClientBasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace ClientBasicData.Api.Application.Handler
{
    /// <summary>
    /// 客户信息录入处理类
    /// </summary>
    public class CreateClientHandler : IRequestHandler<CreateClientCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ClientModel> clientRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateClientHandler> logger;

        public CreateClientHandler(IBaseRespository<ClientModel> clientRepo,
            IMapper mapper,
            ILogger<CreateClientHandler> logger)
        {
            this.clientRepo = clientRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(CreateClientCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var model = mapper.Map<ClientModel>(request);
            model.CreateName=request.CreateName;
            model.CreateTime=DateTime.Now;


            var r=await clientRepo.AddAsync(model);
            if (r>0)
            {
                res.Data = r;
                res.Code=ApiEnum.Success;
                res.Msg = "添加成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "添加失败";
            }
            return res;
        }
    }
}
